<template>
  <view class="page">

    <comHead :datas="datasObj">
      <template #headerContent>

      </template>
    </comHead>
    <view class="header_box_slot">
      <view class="rule flex-center ft c-99" @click="openRule">
        <text class="ft ft-22 c-99 mr-8">{{ "使用规则" }}</text>
        <image class="wh-24" src="https://cdn.oss.bon-top.cn/static_bc/images/illus.png"></image>
      </view>
    </view>
    <view class="cont pd-30">
      <view class="item mb-20" :class="'item' + idnex" v-for="(item, idnex) in quanList" :key="item.id">
        <view class="flex-center ft1 pd-20">
          {{ ((idnex + 1) < 10 ? `0${(idnex + 1)}` : (idnex + 1)) }} <text class="ml-8">{{ item.type_name }}</text>
        </view>
        <view class="proje pd-20">
          <view v-if="item.pack_type === 1">
            <view class="ft1 flex-center">{{ item.txt }}</view>
            <view class="flex-center mt-30"><text class="ft1">{{ item.currency_symbol }}</text>
              <text class="ft-num money">{{
                item.reduce }}</text>
            </view>
            <view class="btn mt-20 auto flex-center ft1 c-dbf" v-if="item.is_get === 0" @click="getCoupon(item.id)">
              领取
            </view>
            <view class="btn1 mt-20 auto flex-center ft1 c-99" v-else>已领取</view>
            <view class="ft c-66 flex-center mt-20">{{
              "首页 - 老师更多 - 列表 - 选择老师 - 预约咨询"
            }}</view>
            <view class="ft ft-22 flex-center mt-10 c-99">{{
              "领取后使用时效为领取后1周内"
            }}</view>
          </view>
          <view v-if="item.pack_type === 2">
            <view class="bc_price_box_three">
              <swiper class="swiper bd-r40" circular :indicator-dots="false" :autoplay="autoplay" :interval="interval"
                :duration="duration" @change="changeSwiper">
                <swiper-item v-for="(couponItem, index) in item.product" :key="index">
                  <view class="card">
                    <view class="flex">
                      <image class="img mr-20" :src="couponItem.cover" mode="aspectFill"></image>
                      <view>
                        <view class="title_model mt-10 flex">
                          <view class="label flex-center ft-20" v-for="label in couponItem.recommends_show"
                            :key="label">
                            {{ label }}
                          </view>

                          <view class="title ft-lue ft1">{{ couponItem.name }}</view>
                        </view>


                        <view class="mt-10">
                          <text class="ft ft-22 c-33">{{ couponItem.currency_symbol }}</text>
                          <text class="ft-num ft-36">{{ couponItem.bc_price_show }}</text>
                          <text class="ft ft-22 c-33">{{ couponItem.bc_price_unit }}</text>
                          <text class="ft ft-22 c-99 ft-hen">{{
                            couponItem.currency_symbol
                          }}</text><text class="ft-num ft-22 c-99 ft-hen">{{
                              couponItem.peer_price_show
                            }}</text><text class="ft ft-22 c-99 ft-hen">{{
                              couponItem.peer_price_unit
                            }}</text>
                        </view>
                        <view class="mt-10 flex">
                          <view class="na flex-center ft-22 ft c-ff">优惠券</view>
                          <view class="pr flex-center ft-22 c-33">{{
                            couponItem.countData.currency_symbol + couponItem.countData.reduce
                          }}</view>
                        </view>
                      </view>
                    </view>
                    <view class="ft ft-22 c-99 flex-center mt-20">
                      支付时使用时效为领取后1周内</view>
                  </view>
                </swiper-item>
              </swiper>
              <view class="indicator">
                <view class="dian" v-for="(item, index) in item.product" :key="index"
                  :class="index == currentIndex ? 'active' : ''"></view>
              </view>
            </view>

            <view class="btn auto flex-center ft1 c-dbf" v-if="item.is_get === 0" @click="getCoupon(item.id)">领取
            </view>
            <view class="btn1 auto flex-center ft1 c-99" v-else>已领取</view>
          </view>
          <view v-if="item.pack_type === 3">
            <view class="ft1 flex-center">{{ item.txt }}</view>
            <view class="flex-center mt-30"><text class="ft1">{{ item.currency_symbol }}</text><text
                class="ft-num money">{{
                  item.reduce }}</text></view>
            <view class="offic pd-20 flex-bwt mt-20">
              <view class="flex">
                <image v-if="item.file_info.suffix === 'pdf'" class="img mr-20"
                  src="https://cdn.oss.bon-top.cn/static_bc/images/PDF.png"></image>
                <image v-if="
                  item.file_info.suffix === 'doc' ||
                  item.file_info.suffix === 'docx'
                " class="img mr-20" src="https://cdn.oss.bon-top.cn/static_bc/images/W.png"></image>
                <image v-if="
                  item.file_info.suffix === 'xls' ||
                  item.file_info.suffix === 'xlsx'
                " class="img mr-20" src="https://cdn.oss.bon-top.cn/static_bc/images/X.png"></image>
                <view>
                  <view class="ft1"> {{ item.file_info.origin_name }}</view>
                  <view class="ft c-99 mt-10">
                    {{ item.file_info.size_info }}</view>
                </view>
              </view>
              <!-- <view class="ft c-99" @click="downloadFile(item.file_info.url)">
                点击下载</view> -->
              <view class="ft c-99" @click="item.is_get === 0 ? '' : openContract(item.file_info)">
                点击下载</view>
            </view>
            <view class="btn mt-20 auto flex-center ft1 c-dbf" v-if="item.is_get === 0" @click="getCoupon(item.id)">
              领取
            </view>
            <view class="btn1 mt-20 auto flex-center ft1 c-99" v-else>已领取</view>
          </view>
          <view v-if="item.pack_type === 4">
            <view class="ft1 flex-center">{{ item.txt }}</view>
            <view class="flex-center mt-20"><text class="ft1">{{ item.currency_symbol }}</text><text
                class="ft-num money">{{
                  item.reduce }}</text></view>
            <view class="vip pd-20 flex-bwt">
              <view>
                <view class="flex">
                  <image class="w42h-36" src="https://cdn.oss.bon-top.cn/static_bc/images/vipIcon.png"></image>
                  <text class="ft1 c-ff ml-8">{{
                    userInfo?.u_info?.is_vip === 1
                      ? userInfo.u_info.level_info.name
                      : "会员权益"
                  }}</text>
                </view>
                <view class="mt-10 ft c-dbf">{{
                  userInfo?.u_info?.is_vip === 1
                    ? userInfo.u_info.expire_time_show
                    : "开通会员，即刻享白菜超底价"
                }}</view>
              </view>
              <view class="vipBtn flex-center">
                <text class="ft c-33 mr-8" @click="goBuyVip">{{
                  userInfo?.u_info?.is_vip === 1 ? "去续期" : "去开通"
                }}</text>
                <image class="wh-24" src="https://cdn.oss.bon-top.cn/static_bc/images/icon_left.png"></image>
              </view>
              <view class="pso ft c-ff flex-center">{{
                "专享白菜价 | 一对一专业老师 | 专属客服"
              }}</view>
            </view>
            <view class="btn mt-20 auto flex-center ft1 c-dbf" v-if="item.is_get === 0" @click="getCoupon(item.id)">
              领取
            </view>
            <view class="btn1 mt-20 auto flex-center ft1 c-99" v-else>已领取</view>
            <view class="ft-22 c-99 text_center mt-20">支付时使用时效为领取后1周内</view>
          </view>
        </view>
      </view>
      <view style="height: 68rpx;"></view>
    </view>
    <up-modal :style="{ width: '270rpx' }" :show="show" :title="title">
      <view class="slot-content">
        <view class="ner pd-20">
          <view class="ft1">使用规则说明</view>
          <view class="ft mt-10 c-66">分享内容项目，视频，老师，直播，国家介绍，资讯，课堂时，微信朋友打开查看后，为完成1次任务。</view>
        </view>
      </view>
      <template #confirmButton>
        <view @click="show = false" class="btn1 auto flex-center ft c-dbf">知道了</view>
      </template>
    </up-modal>
  </view>
  <!-- 合同查看确认弹窗 -->
  <view class="delete_box" ref="diaLogPop" v-if="showContract">
    <view class="bg"></view>
    <view class="delete_model bd-r40">
      <view class="ft-32 c-33 fw-800 mt-30">{{ '提示' }}</view>
      <view class="c-99 ft-28 text pd-30">
        <view>是否查看文档</view>
        <view style="color: #1F18EE;"> 《{{ dataContract.origin_name }}》</view>
        <view>合同大小：{{ dataContract.size_info }} </view>

      </view>
      <view class="btn_model flex-eve">
        <view class="btns" @click="showContract = false">{{ '取消' }}</view>
        <view class="btns sunbmit" @click="downloadFile">{{ '查看' }}</view>
      </view>
    </view>
  </view>
</template>

<script setup lang="js">
import { ref, reactive, onMounted } from "vue";
import { utils } from "@/utils/utils.js";
import { api } from "@/utils/api.js";

import { onLoad, onPageScroll, } from "@dcloudio/uni-app";
import comHead from '@/components/comHead.vue'
let datasObj = reactive({
  title: '新人礼包',
  img: 'https://cdn.oss.bon-top.cn/static_bc/images/xr_bg.png',
  color: `#fff`,
  isColor: true,
  direction: '',
  scrollTop: 0,
  height: 532,
  backisImg: true,//导航文字模块的背景图
  headerisImg: true,//整个huader模块的背景图
  fullImag: true,//header是否显示完整的图片
  imgHeight: 716
})
let currentIndex = ref(0)
let autoplay = ref(false)
let interval = ref(2500)
let duration = ref(500)
// 轮播
const changeSwiper = (e) => {
  currentIndex.value = e.detail.current

}
const show = ref(false);
const title = ref('使用规则');
const openRule = () => {
  show.value = true;
}

const quanList = ref([])
const getCoupon = (id) => {
  console.log('领取优惠券', id)
  utils
    .request(
      api.receiveCoupon,
      {
        is_all: 0,
        is_newcomer: 1,
        ids: [id],
        is_week: 0
      },
      "post"
    )
    .then((res) => {
      if (res.code === 200) {
        utils.toast('领取成功')
        getQuanList()
      }

    });
}
const getQuanList = () => {
  console.log('哈哈哈哈哈哈哈')
  utils
    .request(
      api.getNewcomerCouponList,
      {},
      "get"
    )
    .then((res) => {

      console.log('礼包', quanList.value, res.data.list)
      quanList.value = res.data.list;

    });
}
const downloadProgress = ref(0);
const statusMessage = ref('');
const showContract = ref(false)
const dataContract = ref({})
const openContract = (data) => {
  dataContract.value = data
  showContract.value = !showContract.value
}
const downloadFile = () => {
  showContract.value = !showContract.value

  uni.downloadFile({
    url: dataContract.value.url,
    success: (res) => {
      if (res.statusCode === 200) {
        const filePath = res.tempFilePath;
        console.log('文件下载成功:', filePath);
        // 可以在这里进行进一步的处理，比如保存文件或打开文件
        // 2. 保存文件处理（兼容iOS）
        if (filePath) {
          statusMessage.value = '下载完成，正在保存...';
          uni.showToast({
            title: statusMessage.value,
            icon: 'none'
          });
          // 方案一：直接打开文件（iOS用户可通过分享菜单保存）
          wx.openDocument({
            filePath: filePath,
            showMenu: true, // 关键参数：显示iOS的保存菜单
            fileType: getFileType(dataContract.value.url),
            success: () => {
              statusMessage.value = '请使用右上角菜单保存文件'
              uni.showToast({
                title: statusMessage.value,
                icon: 'none'
              });
            },
            fail: () => saveToLocal(filePath)
          });
        }
        // } catch (error) {
        //   statusMessage.value = error.message || '操作失败';
        // }
        // uni.saveFile({
        //   tempFilePath: filePath,
        //   success: (saveRes) => {
        //     console.log('文件保存成功:', saveRes.savedFilePath);
        //     uni.showToast({
        //       title: '文件下载并保存成功',
        //       icon: 'none'
        //     });
        //   },
        // })
      }
    }
  })
}
// 保存到本地缓存（备用方案）
const saveToLocal = async (tempPath) => {
  try {
    const fs = wx.getFileSystemManager();
    const savePath = `${wx.env.USER_DATA_PATH}/${Date.now()}${getFileExt(tempPath)}`;

    fs.saveFileSync(tempPath, savePath);
    statusMessage.value = `已保存至本地缓存路径: ${savePath}`;
    uni.showToast({
      title: statusMessage.value,
      icon: 'none'
    });
  } catch (error) {
    throw new Error('文件保存失败');
  }
};
// 获取文件类型
const getFileType = (url) => {
  const ext = url.split('.').pop()?.toLowerCase();
  return ({
    pdf: 'pdf',
    doc: 'msword',
    docx: 'msword',
    xls: 'excel',
    xlsx: 'excel'
  })[ext] || 'other';
};

// 获取文件扩展名
const getFileExt = (path) => {
  return path.slice(path.lastIndexOf('.'));
};
const userInfo = ref({});
const isLogin = ref(false);
const getUserData = () => {
  utils.request(api.myCenter, {}, "get").then((res) => {
    isLogin.value = true;
    userInfo.value = res.data.info;
  });
};

const goBuyVip = () => {
  uni.navigateTo({
    url: "/subpackage/openVip/openVip",
  });
}
onPageScroll((e) => {
  // console.log('hhhhh')
  const scrollTop = e.scrollTop; // 获取滚动距离
  // console.log('滚动距离', e.detail)
  // 优化监听事件 防止毫秒级触发
  datasObj.direction = (scrollTop > datasObj.scrollTop) ? 'down' : 'up'
  if (scrollTop > 10 && datasObj.direction == 'down' && datasObj.backisImg) {
    datasObj.color = '#FFFFFF'
    datasObj.backisImg = false
    datasObj.isBoxHeightAuto = true

    datasObj.scrollTop = scrollTop
    // console.log('我是向下滑动')

  } else if (scrollTop < 5 && datasObj.direction == 'up' && !datasObj.backisImg) {
    datasObj.color = '#DBF046'
    datasObj.backisImg = true
    datasObj.isBoxHeightAuto = false
    datasObj.scrollTop = scrollTop
    // console.log('我是向上滑动^^^')

  }
})
onMounted(() => {

})
onLoad(() => {
  getQuanList()
  getUserData()
})
</script>

<style lang="scss" scoped>
.header_box_slot {
  // height: 540rpx;

  top: 208rpx;
  right: 0;
  position: fixed;
  z-index: 100;

  .rule {
    width: 154rpx;
    height: 52rpx;
    background: #feddb0;
    border-radius: 40rpx 0rpx 0rpx 40rpx;
    // position: absolute;
    // right: 0;
    // top: 32rpx;
  }
}

.swiper {
  height: 266rpx;
  overflow: hidden;
  // background-color: red;
  // padding: 20rpx 20rpx 0;
}

.head {
  width: 750rpx;
  height: 716rpx;
  background-image: url("https://cdn.oss.bon-top.cn/static_bc/images/xr_bg.png");
  background-size: 100% 100%;
  position: relative;

  .rule {
    width: 154rpx;
    height: 52rpx;
    background: #feddb0;
    border-radius: 40rpx 0rpx 0rpx 40rpx;
    // position: absolute;
    // right: 0;
    // top: 32rpx;
  }
}

.indicator {
  height: 50rpx;
  display: flex;
  justify-content: center;
  align-items: center;

  .dian {
    width: 10rpx;
    height: 10rpx;
    background-color: #D1D1D1;
    border-radius: 50%;
    margin: 5rpx;
  }

  .active {
    width: 30rpx;
    height: 10rpx;
    background-color: #333333;
    border-radius: 4rpx;
    transition: 0.1s;

  }
}

.cont {


  .item {
    width: 100%;
    height: 514rpx;
    background: linear-gradient(90deg, #dbf046 0%, #ffba61 100%);
    border-radius: 40rpx;
    position: relative;
    overflow: hidden;
    /* 关键属性 */



    .proje {
      width: 100%;
      height: 434rpx;
      background: #f8f8f8;
      border-radius: inherit;
      /* 继承父级圆角 */
      box-sizing: border-box;
      /* 避免padding/margin溢出 */
      // border-radius: 40rpx 40rpx 40rpx 40rpx;
      position: absolute;
      bottom: -0;

      .money {
        font-size: 68rpx;
      }

      .vip {
        position: relative;
        width: 650rpx;
        height: 120rpx;
        background: #333333;
        border-radius: 20rpx 20rpx 20rpx 20rpx;
        background-image: url("https://cdn.oss.bon-top.cn/static_bc/images/vipBg.png");
        background-size: 100% 100%;
        margin-top: 64rpx;

        .vipBtn {
          width: 142rpx;
          height: 72rpx;
          background: #dbf046;
          border-radius: 20rpx 20rpx 20rpx 20rpx;
        }

        .pso {
          position: absolute;
          top: -34rpx;
          width: 430rpx;
          height: 44rpx;
          background: linear-gradient(180deg, #5a54ff 0%, #2b24db 100%);
          border-radius: 10rpx 20rpx 10rpx 20rpx;
        }
      }

      .offic {
        width: 650rpx;
        height: 116rpx;
        background: #ffffff;
        border-radius: 20rpx 20rpx 20rpx 20rpx;

        .img {
          width: 66rpx;
          height: 76rpx;
        }
      }

      .card {
        width: 100%;
        height: 100%;
        background: #ffffff;
        // background-color: red;
        border-radius: 40rpx;
        // border: #dbf046 solid 2rpx;
        padding: 20rpx;

        .title_model {
          display: flex;

          .label {
            border-radius: 8rpx;
            padding: 0 4rpx;
            height: 36rpx;
            display: inline-block;
            line-height: 36rpx;
            box-sizing: border-box;
            margin-right: 4rpx;
            color: #333333;
            background: linear-gradient(to right, #DBF046, #FFEE7E);
            flex-shrink: 0;

          }

          .text {
            margin-left: 10rpx;
            margin-right: 10rpx;
          }



        }

        .title {
          width: 360rpx;
        }

        .na {
          width: 92rpx;
          height: 46rpx;
          background: #333333;
          border-radius: 8rpx 8rpx 8rpx 8rpx;
        }

        .pr {
          width: 70rpx;
          height: 46rpx;
          background: linear-gradient(90deg, #dbf046 0%, #ffba61 100%);
          border-radius: 8rpx 8rpx 8rpx 8rpx;
        }

        .img {
          width: 142rpx;
          height: 174rpx;
          border-radius: 40rpx;
        }
      }

      .btn {
        width: 448rpx;
        height: 78rpx;
        background: #333333;
        border-radius: 20rpx 20rpx 20rpx 20rpx;
      }

      .btn1 {
        width: 448rpx;
        height: 78rpx;
        background: #f1f1f1;
        border-radius: 20rpx 20rpx 20rpx 20rpx;
      }
    }
  }

  .item0 {
    height: 460rpx;


    .proje {
      height: 380rpx;


    }
  }

  .item1 {
    height: 514rpx;


    .proje {
      height: 434rpx;


    }
  }

  .item2 {
    height: 502rpx;


    .proje {
      height: 422rpx;


    }
  }

  .item3 {
    height: 590rpx;


    .proje {
      height: 516rpx;
      position: absolute;
      bottom: 0;

    }
  }
}

.btn1 {
  width: 448rpx;
  height: 78rpx;
  background: #333333;
  border-radius: 20rpx 20rpx 20rpx 20rpx;
}

.delete_box {
  position: fixed;
  height: 100%;
  width: 100%;
  top: 0;
  left: 0;
  z-index: 9999;


  .bg {
    position: absolute;
    height: 100%;
    width: 100%;
    background-color: #000;
    opacity: 0.5;
    top: 0;
    left: 0;
  }

  .delete_model {
    position: absolute;
    background-color: #fff;
    text-align: center;
    width: 518rpx;
    // height: 386rpx;
    top: calc(50% - (386rpx / 2));
    left: calc(50% - (518rpx / 2));

    .text {
      // padding: 20rpx;
      min-height: 140rpx;
    }

    .btn_model {
      margin-bottom: 30rpx;

      .btns {
        width: 184rpx;
        height: 80rpx;
        line-height: 80rpx;
        border-radius: 20rpx;
        font-size: 28rpx;
        color: #333;
        background-color: #F8F8F8;
      }

      .sunbmit {
        background-color: #333;
        color: #DBF046;
      }
    }
  }

}
</style>
